package com.cq.hd.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cq.hd.common.enums.biz.ActiveStateEnum;
import com.cq.hd.common.enums.biz.OrderStateEnum;
import com.cq.hd.common.enums.biz.PromotionTypeEnum;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.Throw;
import com.cq.hd.member.api.TbBusinessApi;
import com.cq.hd.member.api.vo.BusinessVo;
import com.cq.hd.order.api.TbOrderApi;
import com.cq.hd.order.api.dto.OrderDto;
import com.cq.hd.order.api.vo.OrderAvatarVo;
import com.cq.hd.product.api.dto.*;
import com.cq.hd.product.api.vo.ActiveCollectPageVo;
import com.cq.hd.product.mapper.*;
import com.cq.hd.product.po.*;
import com.cq.hd.product.service.TbActiveCollectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cq.hd.product.service.TbActiveGroupBuyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 活动收藏记录表 服务实现类
 * </p>
 *
 * @author mYunYu
 * @since 2023-12-01
 */
@Service
public class TbActiveCollectServiceImpl extends ServiceImpl<TbActiveCollectMapper, TbActiveCollectPo> implements TbActiveCollectService {

    private final Random random = new Random();

    @Autowired
    private TbActiveMapper activeMapper;

    @Autowired
    private TbActiveDiscountMapper activeDiscountMapper;

    @Autowired
    private TbActiveStepPriceMapper activeStepPriceMapper;

    @Autowired
    private TbActiveRedPacketMapper activeRedPacketMapper;

    @Autowired
    private TbActiveBrowseMapper activeBrowseMapper;

    @Autowired
    private TbActiveBrowseStatisticsMapper activeBrowseStatisticsMapper;

    @Autowired
    private TbBusinessApi businessApi;

    @Autowired
    private TbOrderApi orderApi;

    @Autowired
    private TbActiveGroupBuyService activeGroupBuyService;

    @Override
    public boolean updateState(ActiveCollectUpdateDto activeCollectUpdateDto) {
        // 收藏状态：1-收藏，2-取消收藏
        Integer collectState = activeCollectUpdateDto.getCollectState();
        if (collectState == 1) {
            TbActivePo tbActivePo = activeMapper.selectById(activeCollectUpdateDto.getActiveId());
            if (tbActivePo == null || ActiveStateEnum.NO_RELEASE.getValue().equals(tbActivePo.getActiveState())) {
                Throw.isBusinessException("未找到活动数据");
            }

            // 根据活动时间处理活动状态
            Integer activeState = tbActivePo.getActiveState();
            LocalDateTime now = LocalDateTime.now();
            if (!ActiveStateEnum.NO_RELEASE.getValue().equals(activeState)) {
                LocalDateTime startTime = tbActivePo.getStartTime();
                LocalDateTime endTime = tbActivePo.getEndTime();
                if (startTime.compareTo(now) <= 0 && endTime.compareTo(now) > 0) {
                    activeState = ActiveStateEnum.IN_PROGRESS.getValue();
                } else if (endTime.compareTo(now) <= 0) {
                    activeState = ActiveStateEnum.ENDED.getValue();
                } else if (startTime.compareTo(now) > 0) {
                    activeState = ActiveStateEnum.NO_START.getValue();
                }
            }

            // 如果是未发布/未开始的活动，不能被收藏
            if (ActiveStateEnum.NO_RELEASE.getValue().equals(activeState)) {
                Throw.isBusinessException("不能收藏未发布的活动");
            }

            if (ActiveStateEnum.NO_START.getValue().equals(activeState)) {
                Throw.isBusinessException("不能收藏未开始的活动");
            }

            // 查询是否存在记录
            List<TbActiveCollectPo> activeCollectPoList = baseMapper.selectList(new QueryWrapper<TbActiveCollectPo>().eq("del_state", 0)
                    .eq("active_id", activeCollectUpdateDto.getActiveId()).eq("user_id", activeCollectUpdateDto.getUserId()));
            if (!CollectionUtils.isEmpty(activeCollectPoList)) {
                TbActiveCollectPo tbActiveCollectPo = activeCollectPoList.get(0);
                tbActiveCollectPo.setUpdateTime(LocalDateTime.now());
                baseMapper.updateById(tbActiveCollectPo);
            } else {
                // 添加收藏记录
                TbActiveCollectPo tbActiveCollectPo = new TbActiveCollectPo();
                tbActiveCollectPo.setBusinessId(tbActivePo.getBusinessId());
                tbActiveCollectPo.setActiveId(activeCollectUpdateDto.getActiveId());
                tbActiveCollectPo.setUserId(activeCollectUpdateDto.getUserId());
                tbActiveCollectPo.setCollectTime(LocalDateTime.now());
                tbActiveCollectPo.setCreateTime(LocalDateTime.now());
                int insert = baseMapper.insert(tbActiveCollectPo);
                if (insert == 0) {
                    Throw.isBusinessException("收藏失败");
                }
            }
        } else if (collectState == 2) {
            baseMapper.delete(new QueryWrapper<TbActiveCollectPo>()
                    .eq("active_id", activeCollectUpdateDto.getActiveId())
                    .eq("user_id", activeCollectUpdateDto.getUserId()));
        }

        return true;
    }

    @Override
    public Page<ActiveCollectPageVo> pageActiveCollect(ActiveCollectPageDto activeCollectPageDto) {
        PageHelper.startPage(activeCollectPageDto.getPageNum(), activeCollectPageDto.getPageSize());
        List<ActiveCollectPageVo> activeCollectPageVos = baseMapper.listByDto(activeCollectPageDto);
        if (!CollectionUtils.isEmpty(activeCollectPageVos)) {
            List<Long> activeIds = activeCollectPageVos.stream().map(ActiveCollectPageVo::getId).collect(Collectors.toList());
            List<Long> businessIds = activeCollectPageVos.stream().map(ActiveCollectPageVo::getBusinessId).collect(Collectors.toList());

            // 查询多件多折列表
            Map<Long, List<ActiveDiscountSonDto>> tbActiveDiscountPoMap = new HashMap<>();
            List<ActiveDiscountSonDto> tbActiveDiscountPos = activeDiscountMapper.listByActiveIds(activeIds);
            if (!CollectionUtils.isEmpty(tbActiveDiscountPos)) {
                tbActiveDiscountPoMap = tbActiveDiscountPos.stream().collect(Collectors.groupingBy(ActiveDiscountSonDto::getActiveId));
            }

            // 查询新人首单红包数据
            Map<Long, ActiveRedPacketSonDto> activeRedPacketSonDtoMap = new HashMap<>();
            List<ActiveRedPacketSonDto> activeRedPacketSonDtoList = activeRedPacketMapper.listByActiveIds(activeIds);
            if (!CollectionUtils.isEmpty(activeRedPacketSonDtoList)) {
                activeRedPacketSonDtoMap = activeRedPacketSonDtoList.stream().collect(Collectors.toMap(ActiveRedPacketSonDto::getActiveId, Function.identity(), (k1, k2) -> k2));
            }

            // 查询阶梯价格列表
            Map<Long, List<ActiveStepPriceSonDto>> activeStepPriceSonDtoMap = new HashMap<>();
            List<ActiveStepPriceSonDto> activeStepPriceSonDtos = activeStepPriceMapper.listByActiveIds(activeIds);
            if (!CollectionUtils.isEmpty(activeStepPriceSonDtos)) {
                activeStepPriceSonDtoMap = activeStepPriceSonDtos.stream().collect(Collectors.groupingBy(ActiveStepPriceSonDto::getActiveId));
            }

            // 查询商家数据
            Map<Long, BusinessVo> businessVoMap = new HashMap<>();
            List<BusinessVo> businessVos = businessApi.listByIds(businessIds).unpack();
            if (!CollectionUtils.isEmpty(businessVos)) {
                businessVoMap = businessVos.stream().collect(Collectors.toMap(BusinessVo::getId, Function.identity(), (k1, k2) -> k2));
            }

            // 查询活动浏览数
            Map<Long, List<TbActiveBrowseStatisticsPo>> tbActiveBrowseStatisticsPoMap = new HashMap<>();
            List<TbActiveBrowseStatisticsPo> tbActiveBrowseStatisticsPos = activeBrowseStatisticsMapper.selectList(new QueryWrapper<TbActiveBrowseStatisticsPo>()
                    .eq("del_state", 0)
                    .in("active_id", activeIds));
            if (!CollectionUtils.isEmpty(tbActiveBrowseStatisticsPos)) {
                tbActiveBrowseStatisticsPoMap = tbActiveBrowseStatisticsPos.stream().collect(Collectors.groupingBy(TbActiveBrowseStatisticsPo::getActiveId));
            }

            // 查询收藏的活动的下单用户列表
            Map<Long, List<OrderAvatarVo>> orderAvatarMap = new HashMap<>();
            OrderDto orderDto = new OrderDto();
            orderDto.setActiveIds(activeIds);
            orderDto.setOrderStates(Arrays.asList(OrderStateEnum.WAIT_VERIFY.getValue(),
                    OrderStateEnum.VERIFYING.getValue(),
                    OrderStateEnum.FINISH.getValue(),
                    OrderStateEnum.VERIFIED.getValue()));
            List<OrderAvatarVo> orderAvatarVos = orderApi.listAvatarByDto(orderDto).unpack();
            if (!CollectionUtils.isEmpty(orderAvatarVos)) {
                orderAvatarMap = orderAvatarVos.stream().collect(Collectors.groupingBy(OrderAvatarVo::getActiveId));
            }

            for (ActiveCollectPageVo activeCollectPageVo : activeCollectPageVos) {
                Long id = activeCollectPageVo.getId();
                Long businessId = activeCollectPageVo.getBusinessId();

                List<ActiveDiscountSonDto> activeDiscountSonDtos = tbActiveDiscountPoMap.get(id);
                if (!CollectionUtils.isEmpty(activeDiscountSonDtos)) {
                    activeCollectPageVo.setActiveDiscount(activeDiscountSonDtos);
                }

                ActiveRedPacketSonDto activeRedPacketSonDto = activeRedPacketSonDtoMap.get(id);
                if (activeRedPacketSonDto != null) {
                    activeCollectPageVo.setActiveRedPacket(activeRedPacketSonDto);
                }

                List<ActiveStepPriceSonDto> activeStepPriceSonDtoList = activeStepPriceSonDtoMap.get(id);
                if (!CollectionUtils.isEmpty(activeStepPriceSonDtoList)) {
                    activeCollectPageVo.setActiveStepPrices(activeStepPriceSonDtoList);
                }

                BusinessVo businessVo = businessVoMap.get(businessId);
                if (businessVo != null) {
                    activeCollectPageVo.setBusinessName(businessVo.getBusinessName());
                    activeCollectPageVo.setBusinessShortName(businessVo.getBusinessShortName());
                    activeCollectPageVo.setLogo(businessVo.getLogo());
                }

                List<TbActiveBrowseStatisticsPo> tbActiveBrowseStatisticsPoList = tbActiveBrowseStatisticsPoMap.get(id);
                if (!CollectionUtils.isEmpty(tbActiveBrowseStatisticsPoList)) {
                    activeCollectPageVo.setBrowseNum(tbActiveBrowseStatisticsPoList.stream().mapToLong(TbActiveBrowseStatisticsPo::getBrowseNum).sum());
                }

                int buyNum = 0;
                List<OrderAvatarVo> orderAvatarVoList = orderAvatarMap.get(id);
                if (!CollectionUtils.isEmpty(orderAvatarVoList)) {
                    buyNum = orderAvatarVoList.stream().mapToInt(OrderAvatarVo::getOrderNum).sum();
                }
                activeCollectPageVo.setBuyNum(buyNum);

                List<String> avatars = new ArrayList<>();
                if (!CollectionUtils.isEmpty(orderAvatarVoList)) {
                    if (orderAvatarVoList.size() > 3) {
                        // 随机取3条
                        for (int i = 0; i < 3; i++) {
                            avatars.add(orderAvatarVoList.get(random.nextInt(orderAvatarVoList.size())).getAvatar());
                        }
                    } else {
                        for (OrderAvatarVo orderAvatarVo : orderAvatarVoList) {
                            avatars.add(orderAvatarVo.getAvatar());
                        }
                    }
                }

                activeCollectPageVo.setAvatars(avatars);
            }

            // 拼团活动标识
            processActivesGroupBuyTag(activeCollectPageVos);

        }

        PageInfo<ActiveCollectPageVo> pageInfo = new PageInfo<>(activeCollectPageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    private void processActivesGroupBuyTag(List<ActiveCollectPageVo> dataList) {
        if (CollectionUtils.isEmpty(dataList)) {
            return;
        }
        List<Long> activeIds = dataList.stream()
                .filter(e -> PromotionTypeEnum.GROUP_BUY.name().equals(e.getPromotionType()))
                .map(ActiveCollectPageVo::getId)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(activeIds)) {
            return;
        }
        Map<Long, TbActiveGroupBuyPo> activeIdToGroupBuyInfo = activeGroupBuyService.listByActiveIds(activeIds)
                .stream()
                .collect(Collectors.toMap(TbActiveGroupBuyPo::getActiveId, Function.identity()));
        for (ActiveCollectPageVo pageVo : dataList) {
            TbActiveGroupBuyPo groupBuyInfo = activeIdToGroupBuyInfo.get(pageVo.getId());
            if (groupBuyInfo != null) {
                pageVo.setPromotionLabel(groupBuyInfo.getGroupNum() + "人团");
            }
        }
    }

}
